﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.IO;
using System.DirectoryServices;

namespace NFinal.AutoConfig
{
    public class Config
    {
        public static string appRoot;
        public static string AssemblyTitle;
        public static bool autoGeneration = false;
        public enum IISVersion { 
            IIS6,IIS7,IIS8,Unknown
        }
        public Config(string appRoot)
        {
            Config.appRoot = appRoot;
            string[] fileNames= Directory.GetFiles(appRoot, "*.csproj");
            if (fileNames.Length > 0)
            {
                AssemblyTitle = Path.GetFileNameWithoutExtension(fileNames[0]);
            }
            else
            {
                string temp;
                temp = appRoot.Trim('\\');
                AssemblyTitle = temp.Substring(temp.LastIndexOf('\\') + 1);
            }
        }
        /// <summary>
        /// 设置config
        /// </summary>
        /// <returns></returns>
        public static IISVersion GetIISVersion()
        {
            DirectoryEntry getEntity = new DirectoryEntry("IIS://localhost/W3SVC/INFO");
            try
            {
                double Version = Convert.ToDouble(getEntity.Properties["MajorIISVersionNumber"].Value);
                Console.WriteLine("IIS:"+Version.ToString());
                if (Version <7)
                {
                    return IISVersion.IIS6;
                }
                if (Version >= 7 && Version <8)
                {
                    return IISVersion.IIS7;
                }
                else if (Version >= 8)
                {
                    return IISVersion.IIS8;
                }
                else
                {
                    return IISVersion.Unknown;
                }
            }
            catch
            {
                return IISVersion.Unknown;
            }
        }
        public void ModifyGlobal(string[] apps)
        {
            string registRouterPattern = @"RouteConfig\s*.\s*RegisterRoutes\s*\(";
            string globalFileName = MapPath("/Global.asax.cs");
            if(File.Exists(globalFileName))
            {
                StreamReader globalReader = new StreamReader(globalFileName);
                string globalString=globalReader.ReadToEnd();
                globalReader.Close();
                Regex globalReg=new Regex(registRouterPattern);
                Match globalMat= globalReg.Match(globalString);
                if(globalMat.Success)
                {
                    string ignoreRoute=string.Empty;
                    for(int i=0;i<apps.Length;i++)
                    {
                        if(globalString.IndexOf(string.Format("\"{0}/{{*pathInfo}}\"",apps[i]))<0)
                        {
                            ignoreRoute+=string.Format("RouteTable.Routes.Add(new Route(\"{0}/{{*pathInfo}}\",new StopRoutingHandler()));\r\n\t\t\t",apps[i]);
                        }
                    }
                    globalString= globalString.Insert(globalMat.Index,ignoreRoute);
                    StreamWriter globalWriter = new StreamWriter(globalFileName);
                    globalWriter.Write(globalString);
                    globalWriter.Close();
                }
            }
        }
        public void InitHanderAndModuleAndRouter(string app)
        {
            JinianNet.JNTemplate.ITemplate template = new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.Template.Handler_Init));
            template.Context.TempData["app"] = app;
            template.Context.TempData["project"] = AssemblyTitle;
            template.Render(MapPath("/NFinal/Handler.cs"),System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.Template.Module_Init));
            template.Context.TempData["app"] = app;
            template.Context.TempData["project"] = AssemblyTitle;
            template.Render(MapPath("/NFinal/Module.cs"),System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.Template.Router_Init));
            template.Context.TempData["app"] = app;
            template.Context.TempData["project"] = AssemblyTitle;
            template.Render(MapPath("/Router.cs"), System.Text.Encoding.UTF8);
        }
        public void InitUrlFunction(string app)
        {
            JinianNet.JNTemplate.ITemplate template = new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.Template.Url_Init));
            template.Context.TempData["app"] = app;
            template.Context.TempData["project"] = AssemblyTitle;
            template.Render(MapPath("/Url.cs"), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.Template.Url_Js_Init));
            template.Context.TempData["app"] = app;
            template.Context.TempData["project"] = AssemblyTitle;
            template.Render(MapPath("/Url.js"), System.Text.Encoding.UTF8);
        }
        public void InitConfigJson(string app)
        {
            JinianNet.JNTemplate.ITemplate template = new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.App.config));
            template.Context.TempData["app"] = app;
            template.Render(MapPath("/"+app+"/config.json"),new System.Text.UTF8Encoding(false));
        }
        public void InitExtend(string app)
        {
            JinianNet.JNTemplate.ITemplate template =new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.App.Extension));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(MapPath("/" + app + "/Extend.cs"),System.Text.Encoding.UTF8);
        }
        public string getfileName(string fileName)
        {
            string dir = Path.GetDirectoryName(fileName);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            return fileName;
        }
        public void InitAppData(string app)
        {
            string appDataFolder = MapPath("/" + app + "/Data");
            if (!Directory.Exists(appDataFolder))
            {
                Directory.CreateDirectory(appDataFolder);
                string dir = MapPath("/NFinal/Resource/App_Data");
                if (Directory.Exists(dir))
                {
                    CopyDirectory(dir, appDataFolder);
                }
            }
        }
        public void InitIndexHTML(string app)
        {
            
            if (!File.Exists(MapPath("/IDE.html")))
            {
                StreamWriter sw = new StreamWriter(MapPath("/IDE.html"),false, System.Text.Encoding.UTF8);
                sw.Write(NFinal.Template.Template.IDE);
                sw.Close();
                sw.Dispose();
            }
            if (!File.Exists(MapPath("/" + app + "/Index.html")))
            {
                StreamWriter sw = new StreamWriter(MapPath("/"+app+"/Index.html"),false,System.Text.Encoding.UTF8);
                sw.Write(NFinal.Template.Template.Index);
                sw.Close();
                sw.Dispose();
            }
        }
        public void InitCode(string app)
        {
            JinianNet.JNTemplate.ITemplate template = null;
            template =new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Code.Data.Data.CookieInfo));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Code/Data/CookieInfo.cs")),System.Text.Encoding.UTF8);
            
            template =new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Code.Data.Data.CookieManager_Init));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Code/Data/CookieManager.cs")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Code.Data.Data.SessionInfo));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Code/Data/SessionInfo.cs")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                    System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Code.Data.Data.SessionManager_Init));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Code/Data/SessionManager.cs")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                    System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Code.UserControl.UserControl.Navigator_cs));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Code/UserControl/Navigator.cs")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                    System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Code.UserControl.UserControl.Vcode_cs));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Code/UserControl/Vcode.cs")), System.Text.Encoding.UTF8);
        }
        public void InitWebCompiler(string app)
        {
            JinianNet.JNTemplate.ITemplate template = null;
                template =new JinianNet.JNTemplate.Template(
                    System.Text.Encoding.UTF8.GetString(NFinal.Template.App.App.WebCompiler_aspx));
                template.Context.TempData["project"] = AssemblyTitle;
                template.Context.TempData["app"] = app;
                template.Render(getfileName(MapPath("/" + app + "/WebCompiler.aspx")), System.Text.Encoding.UTF8);

                template = new JinianNet.JNTemplate.Template(
                    System.Text.Encoding.UTF8.GetString(NFinal.Template.App.App.WebCompiler_aspx_cs));
                template.Context.TempData["project"] = AssemblyTitle;
                template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/WebCompiler.aspx.cs")), System.Text.Encoding.UTF8);
        }
        public void CreateAppFolders(string app,string[] folders)
        {
            for (int i = 0; i < folders.Length; i++)
            {
                if (!Directory.Exists(MapPath("/"+app+folders[i])))
                {
                    Directory.CreateDirectory(MapPath("/" + app + folders[i]));
                }
            }
        }
        public void InitFolder(string app)
        {
            string[] folders=new string[]{"/Code",
            "/Content","/Controllers","/Data","/Models","/Models/BLL","/Models/DAL","/Models/Tips","/Models/Entity","/Views","/Web"};
            CreateAppFolders(app, folders);
        }
        public void InitModels(string app)
        {

            JinianNet.JNTemplate.ITemplate template =new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Models.Models.Common_cs));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Models/Common.cs")), System.Text.Encoding.UTF8);
        }
        public void InitViews(string app)
        {

            StreamWriter sw = new StreamWriter(MapPath("/" + app + "/Views/Web.config"), false, System.Text.Encoding.UTF8);
            sw.Write( 
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Views.Views.Web_config));
            sw.Close();
            sw.Dispose();
            JinianNet.JNTemplate.ITemplate template = null;
            template =new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Views.Default.Common.Public.Public.Error_aspx));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Views/Default/Common/Public/Error.aspx")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Views.Default.Common.Public.Public.Error_aspx_cs));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Views/Default/Common/Public/Error.aspx.cs")), System.Text.Encoding.UTF8);

            template =new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Views.Default.Common.Public.Public.Footer_ascx));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Views/Default/Common/Public/Footer.ascx")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Views.Default.Common.Public.Public.Footer_ascx_cs));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Views/Default/Common/Public/Footer.ascx.cs")), System.Text.Encoding.UTF8);

            template =new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Views.Default.Common.Public.Public.Header_ascx));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Views/Default/Common/Public/Header.ascx")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Views.Default.Common.Public.Public.Header_ascx_cs));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Views/Default/Common/Public/Header.ascx.cs")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
            System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Views.Default.Common.Public.Public.KindEditorLibrary_ascx));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Views/Default/Common/Public/KindEditorLibrary.ascx")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Views.Default.Common.Public.Public.KindEditorLibrary_ascx_cs));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Views/Default/Common/Public/KindEditorLibrary.ascx.cs")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Views.Default.Common.Public.Public.Navigator_ascx));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Views/Default/Common/Public/Navigator.ascx")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Views.Default.Common.Public.Public.Navigator_ascx_cs));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Views/Default/Common/Public/Navigator.ascx.cs")), System.Text.Encoding.UTF8);

            template =new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Views.Default.Common.Public.Public.Success_aspx));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Views/Default/Common/Public/Success.aspx")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Views.Default.Common.Public.Public.Success_aspx_cs));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Views/Default/Common/Public/Success.aspx.cs")), System.Text.Encoding.UTF8);

            template =new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Views.Default.IndexController.Index.Index_aspx));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Views/Default/IndexController/Index.aspx")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Views.Default.IndexController.Index.Index_aspx_cs));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Views/Default/IndexController/Index.aspx.cs")), System.Text.Encoding.UTF8);
        }
        public void InitWeb(string app)
        {
            JinianNet.JNTemplate.ITemplate template = null;
            template =new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Web.Default.Common.Public.Public.Error_cs));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Web/Default/Common/Public/Error.cs")), System.Text.Encoding.UTF8);
            
            template =new JinianNet.JNTemplate.Template(
                NFinal.Template.App.Web.Default.Common.Public.Public.Error);
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Web/Default/Common/Public/Error.html")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Web.Default.Common.Public.Public.Footer_cs));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Web/Default/Common/Public/Footer.cs")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                NFinal.Template.App.Web.Default.Common.Public.Public.Footer);
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Web/Default/Common/Public/Footer.html")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Web.Default.Common.Public.Public.Header_cs));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Web/Default/Common/Public/Header.cs")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                NFinal.Template.App.Web.Default.Common.Public.Public.Header);
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Web/Default/Common/Public/Header.html")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Web.Default.Common.Public.Public.KindEditor_cs));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Web/Default/Common/Public/KindEditor.cs")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                NFinal.Template.App.Web.Default.Common.Public.Public.KindEditor);
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Web/Default/Common/Public/KindEditor.html")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Web.Default.Common.Public.Public.Navigator_cs));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Web/Default/Common/Public/Navigator.cs")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                NFinal.Template.App.Web.Default.Common.Public.Public.Navigator);
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Web/Default/Common/Public/Navigator.html")), System.Text.Encoding.UTF8);

            template =new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Web.Default.Common.Public.Public.Success_cs));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Web/Default/Common/Public/Success.cs")), System.Text.Encoding.UTF8);

            template =new JinianNet.JNTemplate.Template(
                NFinal.Template.App.Web.Default.Common.Public.Public.Success);
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Web/Default/Common/Public/Success.html")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Web.Default.Common.VCode.VCode.GetVerifyImage_cs));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Web/Default/Common/VCode/GetVerifyImage.cs")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                NFinal.Template.App.Web.Default.Common.VCode.VCode.GetVerifyImage);
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Web/Default/Common/VCode/GetVerifyImage.html")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Web.Default.Common.VCode.VCode.VCheck_cs));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Web/Default/Common/VCode/VCheck.cs")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                NFinal.Template.App.Web.Default.Common.VCode.VCode.VCheck);
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Web/Default/Common/VCode/VCheck.html")), System.Text.Encoding.UTF8);

            template =new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Web.Default.IndexController.IndexController.Index_cs));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Web/Default/IndexController/Index.cs")), System.Text.Encoding.UTF8);

            template =new JinianNet.JNTemplate.Template(
                NFinal.Template.App.Web.Default.IndexController.IndexController.Index);
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Web/Default/IndexController/Index.html")), System.Text.Encoding.UTF8);
        }
        void CopyDirectory(string SourcePath,string DestinationPath)
        {
　　        //创建所有目录
            foreach (string dirPath in Directory.GetDirectories(SourcePath, "*", SearchOption.AllDirectories))
            {
                Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));
            }
　　        //复制所有文件
           foreach (string newPath in Directory.GetFiles(SourcePath, "*.*", SearchOption.AllDirectories))
           {
               if (!File.Exists(newPath.Replace(SourcePath, DestinationPath)))
               {
                   File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath));
               }
           }
        }
        public void InitContent(string app)
        {
            CopyDirectory(MapPath("/NFinal/Content"),MapPath("/"+app+"/Content"));
        }
        public void InitControllerBaseClass(string app)
        {
            JinianNet.JNTemplate.ITemplate template = null;
            template = new JinianNet.JNTemplate.Template(
            System.Text.Encoding.UTF8.GetString(NFinal.Template.App.App.Controller));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Controller.cs")), System.Text.Encoding.UTF8);
        }
        public void InitControllers(string app)
        {
            JinianNet.JNTemplate.ITemplate template = null;
            template =new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Controllers.Common.Common.Public_cs));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Controllers/Common/Public.cs")), System.Text.Encoding.UTF8);

            template = new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Controllers.Common.Common.VCode_cs));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Controllers/Common/VCode.cs")), System.Text.Encoding.UTF8);

            template =new JinianNet.JNTemplate.Template(
                System.Text.Encoding.UTF8.GetString(NFinal.Template.App.Controllers.Controllers.IndexController_cs));
            template.Context.TempData["project"] = AssemblyTitle;
            template.Context.TempData["app"] = app;
            template.Render(getfileName(MapPath("/" + app + "/Controllers/IndexController.cs")), System.Text.Encoding.UTF8);
        }
        /// <summary>
        /// 把基于网站根目录的绝对路径改为相对路径
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string MapPath(string url)
        {
            return appRoot + url.Trim('/').Replace('/', '\\');
        }
        public static void SetAutoCreateConfig(bool autoGen)
        {
            string projectFileName = MapPath("/" + AssemblyTitle + ".csproj");
            bool changed = false;

            if (File.Exists(projectFileName))
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(projectFileName);
                XmlNamespaceManager xmanager = new XmlNamespaceManager(doc.NameTable);
                string nameSpace = doc.DocumentElement.Attributes["xmlns"].Value;
                xmanager.AddNamespace("x", nameSpace);

                XmlNode nodePostBuildEvent = doc.SelectSingleNode("/x:Project/x:PropertyGroup/x:PostBuildEvent", xmanager);
                if (autoGen)
                {
                    if (nodePostBuildEvent == null)
                    {
                        changed = true;
                        nodePostBuildEvent = doc.CreateElement("PostBuildEvent", nameSpace);
                        nodePostBuildEvent.InnerText = "$(ProjectDir)NFinal\\WebCompiler.exe";
                        XmlNode nodePropertyGroup = doc.CreateElement("PropertyGroup", nameSpace);
                        nodePropertyGroup.AppendChild(nodePostBuildEvent);
                        doc.DocumentElement.AppendChild(nodePropertyGroup);
                    }
                    else
                    {
                        if (nodePostBuildEvent.InnerText == string.Empty)
                        {
                            changed = true;
                            nodePostBuildEvent.InnerText = "$(ProjectDir)NFinal\\WebCompiler.exe";
                        }
                    }
                }
                else
                {
                    if (nodePostBuildEvent != null)
                    {
                        changed = true;
                        nodePostBuildEvent.ParentNode.RemoveChild(nodePostBuildEvent);
                    }
                }
                if (changed)
                {
                    doc.Save(projectFileName);
                }
            }
        }

        public static XmlNode CreateXMLPath(XmlDocument doc, string root)
        {
            string[] pathes = root.Trim('/').Split('/');
            string oldXpath = "", newXpath = "";
            if (pathes.Length > 1)
            {
                newXpath = pathes[0];
                XmlNode newNode = null, oldNode = null;
                for (int i = 1; i < pathes.Length; i++)
                {
                    oldXpath = newXpath;
                    newXpath += "/" + pathes[i];
                    newNode = doc.SelectSingleNode(newXpath);

                    oldNode = doc.SelectSingleNode(oldXpath);
                    if (newNode == null)
                    {
                        newNode = doc.CreateElement(pathes[i]);
                        oldNode.AppendChild(newNode);
                    }
                }
                return newNode;
            }
            return doc.DocumentElement;
        }
        public static void SetWebApp(string App)
        { 
            
        }

        /// <summary>
        /// 获取所有的应用模块
        /// </summary>
        /// <returns></returns>
        public static string[] GetApps(string appRoot)
        {
            string[] dirs = Directory.GetDirectories(appRoot);
            string configJsonFileName = string.Empty;
            System.Collections.Generic.List<string> apps = new System.Collections.Generic.List<string>();
            for (int i = 0; i < dirs.Length; i++)
            {
                configJsonFileName = System.IO.Path.Combine(dirs[i], "config.json");
                if (File.Exists(configJsonFileName))
                {
                    apps.Add(System.IO.Path.GetFileName(dirs[i]));
                }
            }
            return apps.ToArray();
        }
        //自动配置WebConfig
        public static void SetWebConfig(IISVersion version, string appRoot,string[] Apps)
        {
            Config.appRoot = appRoot;
            Config.AssemblyTitle = new DirectoryInfo(Config.appRoot).Name;
            //文档是否变动
            bool changed = false;
            
            //配置.net信息
            string webConfig = MapPath("/Web.config");
            if (!File.Exists(webConfig))
            {
                changed = true;
                StreamWriter sw = new StreamWriter(MapPath("/Web.config"), false, System.Text.Encoding.UTF8);
                sw.Write(NFinal.Template.Template.Web_config);
                sw.Close();
                sw.Dispose();
                sw = new StreamWriter(MapPath("/Web.Debug.config"), false, System.Text.Encoding.UTF8);
                sw.Write(NFinal.Template.Template.Web_config_Debug);
                sw.Close();
                sw.Dispose();
                sw = new StreamWriter(MapPath("/Web.Release.config"), false, System.Text.Encoding.UTF8);
                sw.Write(NFinal.Template.Template.Web_config_Release);
                sw.Close();
                sw.Dispose();
            }
            

            //根据环境配置webconfig
            System.Xml.XmlDocument doc = new XmlDocument();
            doc.Load(webConfig);
            XmlNode root = doc.DocumentElement;
            if (root == null)
            {
                return;
            }
            //禁用VS Browser Link功能
            XmlNode enableBrowserLinkNode= doc.DocumentElement.SelectSingleNode("configuration/appSettings/add[@key='vs:EnableBrowserLink']");
            if (enableBrowserLinkNode == null)
            {
                enableBrowserLinkNode = CreateXMLPath(doc, "configuration/appSettings/add");
            }
            if (enableBrowserLinkNode.Attributes["key"] != null)
            {
                enableBrowserLinkNode.Attributes["key"].Value = "vs:EnableBrowserLink";
            }
            else
            {
                XmlAttribute enableBrowserLinkAttrKey = doc.CreateAttribute("key");
                enableBrowserLinkAttrKey.Value = "vs:EnableBrowserLink";
                enableBrowserLinkNode.Attributes.Append(enableBrowserLinkAttrKey);
            }
            if (enableBrowserLinkNode.Attributes["value"] != null)
            {
                enableBrowserLinkNode.Attributes["value"].Value = "false";
            }
            else
            {
                XmlAttribute enableBrowserLinkAttrValue = doc.CreateAttribute("value");
                enableBrowserLinkAttrValue.Value = "false";
                enableBrowserLinkNode.Attributes.Append(enableBrowserLinkAttrValue);
            }
            //< !--删除http协议中无用的version头-- >
            XmlNode httpRuntimeNode = doc.DocumentElement.SelectSingleNode("configuration/system.web/httpRuntime");
            if (httpRuntimeNode == null)
            {
                httpRuntimeNode = CreateXMLPath(doc, "configuration/system.web/httpRuntime");
            }
            if (httpRuntimeNode.Attributes["enableVersionHeader"] != null)
            {
                httpRuntimeNode.Attributes["enableVersionHeader"].Value = "false";
            }
            else
            {
                XmlAttribute httpRuntimeEnableVersionHeaderAttr = doc.CreateAttribute("enableVersionHeader");
                httpRuntimeEnableVersionHeaderAttr.Value = "false";
                httpRuntimeNode.Attributes.Append(httpRuntimeEnableVersionHeaderAttr);
            }
            //< !--session重命名-- >
            XmlNode sessionStateNode = doc.DocumentElement.SelectSingleNode("configuration/system.web/sessionState");
            if (sessionStateNode == null)
            {
                sessionStateNode = CreateXMLPath(doc, "configuration/system.web/sessionState");
            }
            if (sessionStateNode.Attributes["cookieName"] != null)
            {
                sessionStateNode.Attributes["cookieName"].Value = "session_id";
            }
            else
            {
                XmlAttribute sessionStateNodeCookieNameAttr = doc.CreateAttribute("cookieName");
                sessionStateNodeCookieNameAttr.Value = "session_id";
                sessionStateNode.Attributes.Append(sessionStateNodeCookieNameAttr);
            }
            //<!--删除无用的http头-->
            XmlNode customHeadersNode = doc.DocumentElement.SelectSingleNode("configuration/system.webServer/httpProtocol/customHeaders");
            if (customHeadersNode == null)
            {
                customHeadersNode = CreateXMLPath(doc, "configuration/system.webServer/httpProtocol/customHeaders");
            }
            customHeadersNode.RemoveAll();
            customHeadersNode.InnerXml = "<clear/>";
            //如果是IIS7,IIS8新版本,要添加system.webserver配置节
            if (version == IISVersion.IIS7 || version == IISVersion.IIS8)
            {
                //取消验证
                XmlNode newValidationNode = doc.DocumentElement.SelectSingleNode("system.webServer/validation");
                if (newValidationNode == null)
                {
                    newValidationNode = CreateXMLPath(doc, "configuration/system.webServer/validation");
                }
                newValidationNode = doc.DocumentElement.SelectSingleNode("system.webServer/validation");
                if (newValidationNode.Attributes["validateIntegratedModeConfiguration"] != null)
                {
                    newValidationNode.Attributes["validateIntegratedModeConfiguration"].Value = "false";
                }
                else
                {
                    XmlAttribute validateIntegratedModeConfigurationAttr= doc.CreateAttribute("validateIntegratedModeConfiguration");
                    validateIntegratedModeConfigurationAttr.Value = "false";
                    newValidationNode.Attributes.Append(validateIntegratedModeConfigurationAttr);
                }                
                //添加NFinal.Handler
                XmlNode newFactoryNode = doc.DocumentElement.SelectSingleNode("system.webServer/handlers/add[@type='NFinal.Handler']");
                //不存在则添加
                if (newFactoryNode == null)
                {
                    changed = true;
                    XmlNode handlersNode = CreateXMLPath(doc, "configuration/system.webServer/handlers");
                    XmlNode NFinalHandlerNode = doc.CreateElement("add");
                    XmlAttribute attrName = doc.CreateAttribute("name");
                    attrName.Value = "NFinalHandler";
                    XmlAttribute attrVerb = doc.CreateAttribute("verb");
                    attrVerb.Value = "*";
                    XmlAttribute attrPath = doc.CreateAttribute("path");
                    attrPath.Value = "*.nf";
                    XmlAttribute attrType = doc.CreateAttribute("type");
                    attrType.Value = "NFinal.Handler";
                    XmlAttribute attrPreCondition = doc.CreateAttribute("preCondition");
                    attrPreCondition.Value = "integratedMode";
                    NFinalHandlerNode.Attributes.RemoveAll();
                    NFinalHandlerNode.Attributes.Append(attrName);
                    NFinalHandlerNode.Attributes.Append(attrVerb);
                    NFinalHandlerNode.Attributes.Append(attrPath);
                    NFinalHandlerNode.Attributes.Append(attrType);
                    NFinalHandlerNode.Attributes.Append(attrPreCondition);
                    handlersNode.AppendChild(NFinalHandlerNode);
                }
                //添加NFinal.Module
                XmlNode newRewriterNode = doc.DocumentElement.SelectSingleNode("system.webServer/modules/add[@name='NFinalModule']");
                if (newRewriterNode == null)
                {
                    changed = true;
                    XmlNode modulesNode = CreateXMLPath(doc, "configuration/system.webServer/modules");
                    XmlNode urlRewriterNode = doc.CreateElement("add");
                    XmlAttribute attrName = doc.CreateAttribute("name");
                    attrName.Value = "NFinalModule";
                    XmlAttribute attrType = doc.CreateAttribute("type");
                    attrType.Value = "NFinal.Module";
                    urlRewriterNode.Attributes.Append(attrName);
                    urlRewriterNode.Attributes.Append(attrType);
                    modulesNode.AppendChild(urlRewriterNode);
                }
            }
            //IIS8下要删除老的配置节点
            if(version==IISVersion.IIS8)
            {
                XmlNode FactoryNode = doc.DocumentElement.SelectSingleNode("system.web/httpHandlers");
                if (FactoryNode != null)
                {
                    FactoryNode.ParentNode.RemoveChild(FactoryNode);
                }
                XmlNode RewriterNode = doc.DocumentElement.SelectSingleNode("system.web/httpModules");
                if (RewriterNode != null)
                {
                    RewriterNode.ParentNode.RemoveChild(RewriterNode);
                }
            }
            //IS6,IIS7下的system.web配置
            if (version == IISVersion.IIS6 || version == IISVersion.IIS7)
            {
                //添加NFinal节点属性
                XmlNode FactoryNode = doc.DocumentElement.SelectSingleNode("system.web/httpHandlers/add[@type='NFinal.Handler']");
                //不存在则添加
                if (FactoryNode == null)
                {
                    changed = true;
                    XmlNode handlersNode = CreateXMLPath(doc, "configuration/system.web/httpHandlers");
                    XmlNode NFinalHandlerNode = doc.CreateElement("add");
                    XmlAttribute attrVerb = doc.CreateAttribute("verb");
                    attrVerb.Value = "*";
                    XmlAttribute attrPath = doc.CreateAttribute("path");
                    attrPath.Value = "*.nf";
                    XmlAttribute attrType = doc.CreateAttribute("type");
                    attrType.Value = "NFinal.Handler";
                    NFinalHandlerNode.Attributes.RemoveAll();
                    NFinalHandlerNode.Attributes.Append(attrVerb);
                    NFinalHandlerNode.Attributes.Append(attrPath);
                    NFinalHandlerNode.Attributes.Append(attrType);
                    handlersNode.AppendChild(NFinalHandlerNode);
                }

                //添加Rewriter节点属性
                XmlNode RewriterNode = doc.DocumentElement.SelectSingleNode("system.web/httpModules/add[@type='NFinal.Module']");
                if (RewriterNode == null)
                {
                    changed = true;
                    XmlNode modulesNode = CreateXMLPath(doc, "configuration/system.web/httpModules");
                    XmlNode urlRewriterNode = doc.CreateElement("add");
                    XmlAttribute attrName = doc.CreateAttribute("name");
                    attrName.Value = "NFinalModule";
                    XmlAttribute attrType = doc.CreateAttribute("type");
                    attrType.Value = "NFinal.Module";
                    urlRewriterNode.Attributes.Append(attrName);
                    urlRewriterNode.Attributes.Append(attrType);
                    modulesNode.AppendChild(urlRewriterNode);
                }
            }
            //IIS6下要删除新的system.webServer的配置
            if (version == IISVersion.IIS6)
            {
                XmlNode newWebServerNode = doc.DocumentElement.SelectSingleNode("system.webServer");
                if (newWebServerNode != null)
                {
                    newWebServerNode.ParentNode.RemoveChild(newWebServerNode);
                }
            }
            //如果文档变动就保存
            if (changed)
            {
                doc.Save(webConfig);
            }
        }
    }
}
